package web.servlet;

import domain.*;
import org.apache.commons.beanutils.BeanUtils;
import service.AdminService;
import service.CategoryService;
import service.LabelService;
import service.impl.AdminServiceImpl;
import service.impl.CategoryServiceImpl;
import service.impl.LabelServiceImpl;
import util.Md5Util;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/*")
public class AdminServlet extends BaseServlet {
    AdminService service = new AdminServiceImpl();

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String verifyCode = request.getParameter("verifyCode");
        String checkCode = CheckCode.getCheckCode(); //实体类中获取
        System.out.println("管理员获取表单：" + verifyCode);
        System.out.println("管理员获取后台：" + checkCode);
        System.out.println(checkCode.equalsIgnoreCase(verifyCode));
        if (!checkCode.equalsIgnoreCase(verifyCode)) {
            request.setAttribute("login_msg", "验证码错误！");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }
        Map<String, String[]> map = request.getParameterMap();
        //ParameterMap cannot be cast to java.lang.String
        //4.封装User对象
        Administrator administrator = new Administrator();
        try {
            BeanUtils.populate(administrator, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //5.调用Service查询
        Administrator loginAdmin = service.login(administrator);
        //6.判断是否登录成功
        if (loginAdmin != null) {
            //登录成功
            checkCode = null;
            System.out.println(administrator);
            request.getSession().setAttribute("admin", loginAdmin);
            response.sendRedirect(request.getContextPath() + "/manage.jsp");
            System.out.println("登录成功");
        } else {
            request.setAttribute("login_msg", "用户名或密码错误！");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }


    public void findUsersByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取参数
        String currentPage = request.getParameter("currentPage");//当前页数
        String rows = request.getParameter("rows");//每页显示条数
        //首次从manage.jsp页面跳转的时候解决currentPage和rows都为空值的问题
        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        if (rows == null || "".equals(rows)) {
            rows = "10";
        }
        //获取条件查询参数
        Map<String, String[]> condition = request.getParameterMap();
        //2.调用Service查询
        PageBean pb = service.findUserByPage(currentPage, rows, condition);
        System.out.println(pb + "---------------->admin/findUserByPage");
        //3.将pageBean存到request
        request.setAttribute("pb", pb);
        request.setAttribute("condition", condition);
        //4.转发到list.jsp
        request.getRequestDispatcher("/userManage.jsp").forward(request, response);
    }


    public void deleteOneUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //2.获取id
        String uid = request.getParameter("uid");
        //3.调用service删除
        service.deleteUser(uid);
        //4.重定向到展示页面
        response.sendRedirect(request.getContextPath() + "/admin/findUsersByPage");
    }

    public void deleteUsers(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String[] Ids = request.getParameterValues("uid");
        service.delSelectedUsersById(Ids);
        //重定向到重新查询所有的Servlet页面,因为不需要共享数据
        response.sendRedirect(request.getContextPath() + "/admin/findUsersByPage");
    }

    public void pageQuery(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String currentPage = request.getParameter("currentPage");
        String rows = request.getParameter("rows");
        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        if (rows == null || "".equals(rows)) {
            rows = "10";
        }
        String code = null;
        int cid = 1; //如果没有找到默认文章分类id为1
        PageBean pb = service.findArticleByPage(currentPage, rows);//所有文章信息
        List<ArticleDetail> list = new ArrayList();
        List<Article> list2 = pb.getList(); // 获取集合元素列表
        for (Article article : list2) {//遍历文章表中的cid和code
            cid = article.getCid();
            code = article.getCode();
            User user = service.findUserByCode(code);
            Category category = service.findCategory(cid);
            ArticleDetail<ArticleDetail> ad = new ArticleDetail<>();
            ad.setUsername(user.getUsername());
            ad.setCname(category.getCname());
            ad.setTitle(article.getTitle());
            ad.setCreateTime(article.getCreateTime());
            ad.setModifyTime(article.getModifyTime());
            ad.setBrowserNum(article.getBrowserNum());
            list.add(ad);
        }
        System.out.println(list + "------------->admin/pageQuery");
        request.getSession().setAttribute("list", list);
        request.getSession().setAttribute("pb", pb);
        request.getRequestDispatcher("/articleManage.jsp").forward(request, response);
    }


    public void updateUsernameAndPassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Administrator adminSession = (Administrator) request.getSession().getAttribute("admin");
        //先判断账号是否重复
        Administrator adminSql = service.findOneAdmin(username);
        //修改账号密码
        if (adminSql == null) {
            int row = service.updateUsernameAndPassword(adminSession.getId(), username, Md5Util.encodeByMd5(password));
            if (row != 0) {
                request.getSession().setAttribute("errorMsg","修改成功！");
                //更新session域中管理员信息
                Administrator admin = service.findOneAdmin(username);
                request.getSession().setAttribute("admin",admin);
            } else {
                request.getSession().setAttribute("errorMsg","修改失败！");
            }
        }else {
            request.getSession().setAttribute("errorMsg","请勿提交与之前相同的账号！");
        }
        request.getRequestDispatcher("/adminManage.jsp").forward(request,response);
    }

    public void pageQueryForCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取参数
        String currentPage = request.getParameter("currentPage");//当前页数
        String rows = request.getParameter("rows");//每页显示条数
        //首次从manage.jsp页面跳转的时候解决currentPage和rows都为空值的问题
        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        if (rows == null || "".equals(rows)) {
            rows = "5";
        }
        //获取条件查询参数
        Map<String, String[]> condition = request.getParameterMap();
        //2.调用Service查询
        PageBean pb = service.findCategoryByPage(currentPage, rows, condition);
        System.out.println(pb + "---------------->admin/pageQueryForCategory");
        //3.将pageBean存到request
        request.setAttribute("pb", pb);
        request.setAttribute("condition", condition);
        request.getRequestDispatcher("/categoryManage.jsp").forward(request, response);
    }

    public void deleteCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cid = request.getParameter("cid");
        service.deleteCategory(cid);
        CategoryService category = new CategoryServiceImpl();
        List<Category> list = category.findAll();
        request.getSession().setAttribute("pb", list);
        request.getRequestDispatcher("admin/pageQueryForCategory").forward(request, response);
    }


    public void addCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cname = request.getParameter("cname");
        service.addCategory(cname);
        CategoryService category = new CategoryServiceImpl();
        List<Category> list = category.findAll();
        request.getSession().setAttribute("pb", list);
        request.getRequestDispatcher("admin/pageQueryForCategory").forward(request, response);
    }

    public void pageQueryForLabel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取参数
        String currentPage = request.getParameter("currentPage");//当前页数
        String rows = request.getParameter("rows");//每页显示条数
        //首次从manage.jsp页面跳转的时候解决currentPage和rows都为空值的问题
        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        if (rows == null || "".equals(rows)) {
            rows = "5";
        }
        //获取条件查询参数
        Map<String, String[]> condition = request.getParameterMap();
        //2.调用Service查询
        PageBean pb = service.findLabelByPage(currentPage, rows, condition);
        System.out.println(pb + "---------------->admin/pageQueryForLabel");
        //3.将pageBean存到request
        request.setAttribute("pb", pb);
        request.setAttribute("condition", condition);
        request.getRequestDispatcher("/labelManage.jsp").forward(request, response);
    }

    public void deleteLabel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String lid = request.getParameter("lid");
        service.deleteLabel(lid);
        LabelService labelService = new LabelServiceImpl();
        List<Label> list = labelService.findAll();
        request.getSession().setAttribute("pb", list);
        request.getRequestDispatcher("admin/pageQueryForLabel").forward(request, response);
    }

    public void addLabel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String lname = request.getParameter("lname");
        service.addLabel(lname);
        LabelService labelService = new LabelServiceImpl();
        List<Label> list = labelService.findAll();
        request.getSession().setAttribute("pb", list);
        request.getRequestDispatcher("admin/pageQueryForLabel").forward(request, response);
    }
}
